package com.fingard.dsp.bank.directbank.boc01;

import java.io.File;
import java.util.*;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.text.StringHelper;
import com.fingard.util.PdfGenerateUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by marlon on 2018/3/6.
 */
public class BOC01Receipt extends BOC01Base implements IReceipt {

    //交易传入的数据
    private String receiptSaveToMainDir = "";

    public RetAtsReceipt qryReceipt(ReqQryReceipt p_reqReceipt) throws Exception {
        //电子回单查询返回ATS的对象
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        receiptSaveToMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
        if (!StringHelper.isNullOrEmpty(receiptSaveToMainDir)) {
            if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptPushServerUrl)) {
                    if (this.getBankConfig().getValueAsBool("isReceiptInterface")) {
                        download_b2e0377(p_reqReceipt);
                    } else {
                        download_b2e0500(p_reqReceipt);
                    }
                    retAts.respCode = "0";
                    retAts.respInfo = "后台处理中";
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "DSPSystem未配置回单文件推送地址";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "DSPSystem未配置回单文件共享目录";
            }
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = "DSPSystem未配置回单文件下载保存主目录";
        }
        retAts.writeRetToATS();
        return retAts;
    }

    public void download_b2e0500(ReqQryReceipt p_reqReceipt) {
        //余额查询返回ATS的对象
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_reqReceipt.getDateTo());
            int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            StringBuilder fileNameList = new StringBuilder();
            int fileCount = 0;
            while (tmpIntFrom <= tmpIntTo) {
                //int intFromStep = tmpIntFrom;
                Date fromDateStep = tmpCalendarFrom.getTime();
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));

                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                calendar.add(Calendar.DAY_OF_MONTH, -2);
                //判断是否要重新下载电子回单
                //if (tmpCalendarFrom.getTime().before(calendar.getTime())) {
                if (new File(receiptSaveToMainDir + File.separator + p_reqReceipt.actNum +
                        File.separator + Format.Date8Format.format(fromDateStep) +
                        File.separator + p_reqReceipt.actNum + "_" + Format.Date8Format.format(fromDateStep) + ".txt").exists()) {
                    WriteBankLogLn(receiptSaveToMainDir + File.separator + p_reqReceipt.actNum +
                            File.separator + Format.Date8Format.format(fromDateStep) +
                            File.separator + p_reqReceipt.actNum + "_" + Format.Date8Format.format(fromDateStep) + ".txt存在，所以账户" + p_reqReceipt.actNum +
                            "在交易日期为" + fromDateStep + "电子回单已下载，无需重复下载，如需再次下载删除本文件即可");
                    continue;
                }
                //}
                BOC01Header bankHeader = new BOC01Header();
                bankHeader.trncod = "b2e0500";//交易代码
                bankHeader.trnid = getQryTransID();//报文编号 字母数字串 0-12位
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入通用的头部节点
                writeCommonHeader(xmlWriter, bankHeader);
                xmlWriter.writeStartElement("trn-b2e0500-rq");
                xmlWriter.writeStartElement("b2e0500-rq");
                xmlWriter.writeElementString("tratype", "A");//交易类型

                xmlWriter.writeStartElement("amtscope");
                xmlWriter.writeElementClosed("minamt");//金额下限
                xmlWriter.writeElementClosed("maxamt");//金额上限
                xmlWriter.writeEndElement();

                xmlWriter.writeStartElement("datescope");
                xmlWriter.writeElementString("from", Format.Date8Format.format(fromDateStep));//开始日期
                xmlWriter.writeElementString("to", Format.Date8Format.format(fromDateStep));//截至日期
                xmlWriter.writeEndElement();

                xmlWriter.writeStartElement("domaccount");
                xmlWriter.writeElementClosed("transact");//交易对方账号
                xmlWriter.writeElementClosed("transname");//对方账户名称
                xmlWriter.writeEndElement();

                xmlWriter.writeElementString("insid", p_reqReceipt.actCur + "_" + Format.DateTime17SSSFormat.format(new Date()));//客户申请号非空
                xmlWriter.writeStartElement("multidata");
                xmlWriter.writeStartElement("confirmdata");
                xmlWriter.writeElementString("actacn", p_reqReceipt.actNum);//查询账号
                xmlWriter.writeElementClosed("ibknum");//联行号

                xmlWriter.writeEndDocument();
                String[] tmpStrRet = new String[]{"", ""};
                WriteBankLogLn("发送银行报文：" + xmlWriter.toXmlString());
                tmpStrRet = sendToBank(xmlWriter.toXmlString());
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String trspcod = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0500-rs/status/rspcod");
                        String trspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0500-rs/status/rspmsg");
                        if ("B001".equals(trspcod)) {
                            String rspcod = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0500-rs/b2e0500-rs/status/rspcod");
                            String rspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0500-rs/b2e0500-rs/status/rspmsg");
                            if ("B001".equals(rspcod)) {
                                String fileName = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0500-rs/b2e0500-rs/filename");//名称
                                fileNameList.append(fileName).append("，");
                                fileCount++;
                            } else {
                                WriteBankLogLn(rspmsg);
                            }
                        } else {
                            WriteBankLogLn(trspmsg);
                        }
                    } else {
                        WriteBankLogLn(tmpSbMsg.toString());
                    }
                } else {
                    WriteBankLogLn(tmpStrRet[1]);
                }
            }
            WriteBankLogLn("成功下载了" + fileCount + "个文件到sftp，名称为：" + fileNameList.toString());
        } catch (Exception e) {
            WriteBankLogLn(e.getMessage());
            e.printStackTrace();
        }
    }

    public void download_b2e0377(ReqQryReceipt p_reqReceipt) {
        //余额查询返回ATS的对象
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_reqReceipt.getDateTo());
            int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            StringBuilder fileNameList = new StringBuilder();
            int fileCount = 0;
            while (tmpIntFrom <= tmpIntTo) {
                //int intFromStep = tmpIntFrom;
                Date fromDateStep = tmpCalendarFrom.getTime();
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));

                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                calendar.add(Calendar.DAY_OF_MONTH, -2);
                //判断是否要重新下载电子回单
                //if (tmpCalendarFrom.getTime().before(calendar.getTime())) {
                if (new File(receiptSaveToMainDir + File.separator + p_reqReceipt.actNum +
                        File.separator + Format.Date8Format.format(fromDateStep) +
                        File.separator + p_reqReceipt.actNum + "_" + Format.Date8Format.format(fromDateStep) + ".txt").exists()) {
                    WriteBankLogLn(receiptSaveToMainDir + File.separator + p_reqReceipt.actNum +
                            File.separator + Format.Date8Format.format(fromDateStep) +
                            File.separator + p_reqReceipt.actNum + "_" + Format.Date8Format.format(fromDateStep) + ".txt存在，所以账户" + p_reqReceipt.actNum +
                            "在交易日期为" + fromDateStep + "电子回单已下载，无需重复下载，如需再次下载删除本文件即可");
                    continue;
                }
                //}
                BOC01Header bankHeader = new BOC01Header();
                bankHeader.trncod = "b2e0377";//交易代码
                bankHeader.trnid = getQryTransID();//报文编号 字母数字串 0-12位
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入通用的头部节点
                writeCommonHeader(xmlWriter, bankHeader);
                xmlWriter.writeStartElement("trn-b2e0377-rq");
                xmlWriter.writeStartElement("b2e0377-rq");
                xmlWriter.writeElementString("tratype", "A");//交易类型

                xmlWriter.writeStartElement("amtscope");
                xmlWriter.writeElementClosed("minamt");//金额下限
                xmlWriter.writeElementClosed("maxamt");//金额上限
                xmlWriter.writeEndElement();

                xmlWriter.writeStartElement("datescope");
                xmlWriter.writeElementString("from", Format.Date8Format.format(fromDateStep));//开始日期
                xmlWriter.writeElementString("to", Format.Date8Format.format(fromDateStep));//截至日期
                xmlWriter.writeEndElement();

                xmlWriter.writeStartElement("domaccount");
                xmlWriter.writeElementClosed("transact");//交易对方账号
                xmlWriter.writeElementClosed("transname");//对方账户名称
                xmlWriter.writeEndElement();

                xmlWriter.writeElementString("insid", p_reqReceipt.actCur + "_" + Format.DateTime17SSSFormat.format(new Date()));//客户申请号非空
                xmlWriter.writeStartElement("multidata");
                xmlWriter.writeStartElement("confirmdata");
                xmlWriter.writeElementString("actacn", p_reqReceipt.actNum);//查询账号
                xmlWriter.writeElementClosed("ibknum");//联行号

                xmlWriter.writeEndDocument();
                String[] tmpStrRet = new String[]{"", ""};
                WriteBankLogLn("发送银行报文：" + xmlWriter.toXmlString());
                tmpStrRet = sendToBank(xmlWriter.toXmlString());
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String trspcod = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0377-rs/status/rspcod");
                        String trspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0377-rs/status/rspmsg");
                        if ("B001".equals(trspcod)) {
                            String rspcod = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0377-rs/b2e0377-rs/status/rspcod");
                            String rspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0377-rs/b2e0377-rs/status/rspmsg");
                            if ("B001".equals(rspcod)) {
                                String fileName = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0377-rs/b2e0377-rs/filename");//名称
                                //记录账户与pdf的关联关系
                                String recordPath = receiptSaveToMainDir + File.separator + p_reqReceipt.actNum + "_" + fileName.replace(".pdf", ".txt");
                                File file = new File(recordPath);
                                if(!file.exists()) {
                                	file.createNewFile();
                                }
                                fileNameList.append(fileName).append("，");
                                fileCount++;
                            } else {
                                WriteBankLogLn(rspmsg);
                            }
                        } else {
                            WriteBankLogLn(trspmsg);
                        }
                    } else {
                        WriteBankLogLn(tmpSbMsg.toString());
                    }
                } else {
                    WriteBankLogLn(tmpStrRet[1]);
                }
            }
            WriteBankLogLn("成功下载了" + fileCount + "个文件到sftp，名称为：" + fileNameList.toString());
        } catch (Exception e) {
            WriteBankLogLn(e.getMessage());
            e.printStackTrace();
        }
    }
}
